﻿@using Huirui.Cavan.Domain.MainBoundedContext.SalesModule
@model Huirui.Cavan.Presentation.ViewModel.SalesModule.ISalesPriceViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.SALESPRICE))
{
    <div class="tool_bar">
        <input id="salesprice_save" type="submit" value="save" style="display: none;" />
        <input id="salesprice_reset" type="reset" style="display: none" />
        <input id="salesprice_query" type="submit" value="query" style="display: none;" />
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'" onclick="javascript:$('#salesprice_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add',disabled:true" onclick="javascript:$('#salesprice_reset').click()">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete',disabled:true">删除</a>
        <a href="#" id="queryPurchaseOrder" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'">查询</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print',disabled:true">打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'"
            onclick="toggleHeard()">折叠/展开</a>
    </div>
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>
                    制单日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.ModifyDate, new { id = "modifyDate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    价格生效日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.StartDate, new { id = "startDate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    价格失效日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.EndDate, new { id = "endDate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    调价单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "code" })
            </td>
            <td class="c100">
                <label>
                    客户:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.CustomersShow, new { id = "customerCodeForSalesPrice" })
            </td>
            <td class="c100">
                <label>
                    调价类型:</label>
            </td>
            <td class="c160">
                @Html.DropDownListFor(m => m.Type, typeof(SalesIdentifier.PriceType), new { id = "type" })
            </td>
            <td class="c100">
                <label>
                    备注:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Remark, new { id = "remark" })
            </td>
        </tr>
    </table> 
    @Html.HiddenFor(m => m.Customers, new { id = "customers" })
    @Html.HiddenFor(m => m.SalesPriceDetails, new { id = "salesPriceDetails" })
}

<table class="sys_param_table" id="selectedStocksForSalesPrice" toolbar="#sale_price_tb">
</table>
<div id="sale_price_tb">
    <a href="#" id="selectStockForSalesPrice" class="easyui-linkbutton" iconcls="icon-checked"
        plain="true" onclick="InitSelectStock('stocksForSalesPrice');openWindow('selectStockWindowForSalesPrice')">选择存货</a>
</div>

@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.STOCK, new { purpose = "ForSalesPrice" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.CUSTOMER, new { purpose = "ForSalesPrice" }); }

<script type="text/javascript">
    $(function () {
        var lastIndex;
        var salesDetails;
        $('#selectedStocksForSalesPrice').datagrid({
            columns: [[
                { field: 'Id', title: '存货编码', width: 100 },
                { field: 'Name', title: '存货名称', width: 80 },
                { field: 'Specification', title: '规格', width: 60 },
                { field: 'UnitTransfer', title: '计量单位', width: 100 },
                { field: 'StandardSalesPrice', title: '单价', width: 100, editor: { type: 'text' } },
                { field: 'DiscountRate', title: '折扣率', width: 100, editor: { type: 'text' } },
                { field: 'SalesCost', title: '成交价 ', width: 80, editor: { type: 'text' } },
                { field: 'Remark', title: '备注', width: 80 }
            ]]
        });

        $("#searchStockForSalesPrice").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksForSalesPrice').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        var currentIndex;
        var currentRow;
        var rowId;
        var standardSalesPrice;
        var discountRate;

        $("#doSelectStockForSalesPrice").bind("click", function () {
            $('#selectedStocksForSalesPrice').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksForSalesPrice').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                insert(rows[i].Id, rows[i].Name, rows[i].Specification, rows[i].UnitTransfer, rows[i].StandardSalesPrice, rows[i].DiscountRate, 0, 'test');
            }
            closeWindow('selectStockWindowForSalesPrice');
        });

        function insert(id, name, specification, unitTransfer, standardSalesPrice, discountRate, salesCost, remark) {
            var rows = $('#selectedStocksForSalesPrice').datagrid('getRows');
            index = -1;
            if (rows.length == 0) {
                index = 0;
            }
            else {
                index = rows.length;
            }

            $('#selectedStocksForSalesPrice').datagrid('insertRow', {
                index: index,
                row: {
                    Id: id,
                    Name: name,
                    Specification: specification,
                    UnitTransfer: unitTransfer,
                    StandardSalesPrice: standardSalesPrice,
                    DiscountRate: discountRate,
                    SalesCost: salesCost,
                    Remark: remark
                }
            });
            $('#selectedStocksForSalesPrice').datagrid('selectRow', index);
            $('#selectedStocksForSalesPrice').datagrid('beginEdit', index);

            var ed = $('#selectedStocksForSalesPrice').datagrid('getEditors', index);
            for (var i = 0; i < ed.length; i++) {
                var e = ed[i];
                if (e.field == "StandardSalesPrice") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForSalesPrice').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        standardSalesPrice = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForSalesPrice').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "DiscountRate") {
                                discountRate = $(this).find("input").val();
                                if (discountRate == '') {
                                    discountRate = 100;
                                }
                            }
                            else if ($(this).attr("field") == "SalesCost") {
                                $(this).find("input").html(standardSalesPrice * (parseFloat(discountRate) / 100));
                            }
                        });
                        $('#selectedStocksForSalesPrice').datagrid('unselectRow', currentIndex);
                    })
                }
                else if (e.field == "DiscountRate") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForSalesPrice').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        discountRate = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForSalesPrice').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "StandardSalesPrice") {
                                standardSalesPrice = $(this).find("input").val();
                            }
                            else if ($(this).attr("field") == "SalesCost") {
                                $(this).find("input").val(parseFloat(standardSalesPrice) * (parseFloat(discountRate) / 100));
                            }
                        });
                        $('#selectedStocksForSalesPrice').datagrid('unselectRow', currentIndex);
                        currentRow.DiscountRate = discountRate;
                    })
                }
                else if (e.field == "SalesCost") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForSalesPrice').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        var salesCost = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForSalesPrice').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "StandardSalesPrice") {
                                standardSalesPrice = $(this).find("input").val();
                            }
                            else if ($(this).attr("field") == "DiscountRate") {
                                $(this).find("input").val(parseFloat(100 * (parseFloat(salesCost) / parseFloat(standardSalesPrice))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForSalesPrice').datagrid('unselectRow', currentIndex);
                        currentRow.DiscountRate = parseFloat(100 * (parseFloat(salesCost) / parseFloat(standardSalesPrice))).toFixed(2);
                    })
                }
            }
        }

        $("form[action^='/salesprice/add']").submit(function () {
            var rows = $('#selectedStocksForSalesPrice').datagrid('getRows');
            salesPriceDetails = "[";
            for (var i = 0; i < rows.length; i++) {
                if (i == (rows.length - 1)) {
                    salesPriceDetails = salesPriceDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, " + "\"UnitCost\" :" + rows[i].StandardSalesPrice + ", \"DiscountRate\" :" + rows[i].DiscountRate + " }";
                }
                else {
                    salesPriceDetails = salesPriceDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, " + "\"UnitCost\" :" + rows[i].StandardSalesPrice + ", \"DiscountRate\" :" + rows[i].DiscountRate + " },";
                }
            }
            salesPriceDetails = salesPriceDetails + "]";
            $("#salesPriceDetails").val(salesPriceDetails);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    if (data.IsSuccess) {
                        alert(data.Messages[0]);
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#customerCodeForSalesPrice").bind("click", function () {
            InitSelectCustomer('customersForSalesPrice');
            openWindow("selectCustomerWindowForSalesPrice");
        });

        $("#searchCustomerForSalesPrice").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#customersForSalesPrice').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectCustomerForSalesPrice").bind("click", function () {
            var customers = "[";
            var currentRow = $('#customersForSalesPrice').datagrid('getSelected');
            if (currentRow.length > 1) {
                $("#customerCodeForSalesPrice").val("多客户");
                for (var i = 0; i < currentRow.length; i++) {
                    if (i == (currentRow.length - 1)) {
                        customers = customers + "{ \"Id\" :" + "\"" + currentRow[i].Id + "\" }";
                    }
                    else {
                        customers = customers + "{ \"Id\" :" + "\"" + currentRow[i].Id + "\" }" + ",";
                    }
                }
               
            }
            else {
                $("#customerCodeForSalesPrice").val(currentRow.Id);
                customers = customers + "{ \"Id\" :" + "\"" + currentRow.Id + "\" }";
            }
            customers = customers + "]";
            $("#customers").val(customers);
            closeWindow("selectCustomerWindowForSalesPrice");
        });
    });
</script>
